﻿using UnityEngine;

public class FSMMachine<T>
{
    public T owner { get; private set; }

    public FSMState<T> currentState { get; private set; }
    public FSMState<T> previousState { get; private set; }
    public FSMState<T> globalState { get; private set; }

    public FSMMachine(T owner)
    {
        Debug.Assert(owner != null);
        this.owner = owner;
    }

    /// <summary>
    /// 循环执行
    /// </summary>
    public void Excute()
    {
        if (globalState != null)
        {
            globalState.Excute(owner);
        }
        if (currentState != null)
        {
            currentState.Excute(owner);
        }
    }

    /// <summary>
    /// 改变状态
    /// </summary>
    /// <param name="stateNew">新状态</param>
    public void ChangeState(FSMState<T> stateNew)
    {
        Debug.Assert(stateNew != null, "FSMMachine:ChangeState() trying to change to a null state!");

        previousState = currentState;
        if (currentState != null)
        {
            currentState.Exit(owner);
        }

        currentState = stateNew;
        currentState.Enter(owner);
    }

    /// <summary>
    /// 回溯前一个状态
    /// </summary>
    public void RevertToPreviousState()
    {
        ChangeState(previousState);
    }
}
